import getComponentRootDom from '@/utils/public/getComponentRootDom';
import styles from './index.module.less';
import icon from '@/components/Icon';
/**
 * 弹出消息
 * @param {String} content 消息内容
 * @param {String} type 消息类型  info  error  success  warn
 * @param {Number} duration 多久后消失
 * @param {HTMLElement} container 容器，消息会显示到该容器的正中；如果不传，则显示到页面正中
 * @param {Function} callback 回调函数，提示消失后才触发
 */

function commonPart(options) {
  const content = options.content || '评论成功';
  const type = options.type || 'info';
  const duration = options.duration || 1300;
  const container = options.container || document.body;

  //判断父容器是否有定位
  if (options.container) {
    if (getComputedStyle(container).position == 'static') {
      container.style.position = 'relative';
    }
  }

  //获取icon根的dom
  const iconRootDom = getComponentRootDom(icon, {
    type
  });

  //创键展视消息容器
  let div = document.createElement('div');
  div.innerHTML = `<span class=${styles.icon}>${iconRootDom.outerHTML}</span><div >${content}</div>`
  div.className = `${styles['showMessage-container']} ${styles['showMessage-container-'+type]}`;

  //插入到容器中
  container.appendChild(div);
  div.clientHeight; //浏览器强行渲染 导致reflow

  //回到位置
  div.style.opacity = 1;
  div.style.transform = `translate(-50%,-50%)`;
  return {
    div,
    ...options
  };
}

//回调模式
export  function showMessage(options = {}) {
  const {div,container,duration,callback} = commonPart(options);
  //等一段duration时间就消失
   setTimeout(()=>{
    div.style.opacity = 0;
    div.style.transform = `translate(-50%,-50%) translateY(-25px)`;

    //消失过渡完成,移除消息容器，并触发回调函数
    container.addEventListener('transitionend',function(){
      div.remove()
      callback && callback();
    },{once:true})
   },duration)
}

// promise模式
export async function asyncShowMessage(options = {}) {
  const {div,container,duration} = commonPart(options);
  return new Promise(resolve => {
    setTimeout(() => {
      div.style.opacity = 0;
      div.style.transform = `translate(-50%,-50%) translateY(-25px)`;

      container.addEventListener('transitionend', () => {
        div.remove()
        resolve();
      }, {
        once: true
      })
    }, duration)
  })
}
